import React, { useEffect, ReactNode } from 'react';
import { useAuthStore, initializeAuthListener, cleanupAuthListener } from '../stores/authStore';

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const initialize = useAuthStore((state) => state.initialize);

  useEffect(() => {
    // 初始化认证状态
    initialize();
    
    // 初始化认证状态监听器
    initializeAuthListener();
    
    // 清理函数
    return () => {
      cleanupAuthListener();
    };
  }, [initialize]);

  return <>{children}</>;
};

// 导出 useAuth hook 以保持向后兼容
export const useAuth = () => {
  const {
    user,
    session,
    profile,
    isAuthenticated,
    loading,
    signIn,
    signUp,
    signOut,
    refreshSession,
  } = useAuthStore();

  return {
    user,
    session,
    profile,
    isAuthenticated,
    loading,
    signIn,
    signUp,
    signOut,
    refreshSession,
  };
};